﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace MedievalGameProject
{
    public class Projectile : Actor
    {
        public static float EPSILON = 0.00005f;

        Character owner;
        float damage;
        bool hitSomething;

        public Projectile(Game game, BasicModel m, Vector3 position, Vector3 direction,
            float speed, float damage, float actorHeight, Character owner)
            : base(game, m, position, actorHeight)
        {
            this.speed = speed;
            this.damage = damage;
            this.owner = owner;
            SetFacingDirection3D(direction);
            usesGravity = true;
            hitSomething = false;
            velocity = direction * speed;

            fallAccel = -0.01f;

            boundingShapes = new BoundingShapes(position, 
                new BoundingBox(new Vector3(-2, -0.5f, -2), new Vector3(2, 0.5f, 2)), GraphicsDevice);
        }

        public override void Update(GameTime gameTime)
        {
            if (!hitSomething)
            {
                base.Update(gameTime);

                Vector3 newDirection = velocity;
                newDirection.Normalize();
                direction = newDirection;

                List<Actor> actorsHit = Game1.actorManager.CheckCollision(this);

                foreach (Actor act in actorsHit)
                {
                    if (act is Character && !act.Equals(owner))
                    {
                        Character character = ((Character)act);
                        character.TakeDamage(damage, owner);
                        hitSomething = true;
                        Game1.actorManager.ScheduleRemoveActor(this);
                    }
                }
            }  
        }

        public override void Move(Vector3 directionToMove)
        {
            Vector3 moveDir = directionToMove;
            moveDir.Normalize();

            Vector3 velocity = directionToMove * speed;

            position += velocity;
        }

        public override void ApplyGravity()
        {
            velocity.Y += fallAccel;
            Move(velocity);

            downRay.Position = position;

            float? distFromGround = Game1.terrain.Intersects(downRay);

            if (distFromGround != null)
            {
                if (distFromGround <= EPSILON + actorHeight)
                    hitSomething = true; ;
            }
        }
    }
}
